/*
 * Copyright 2011 Angel Sanadinov
 *
 * This file is part of VBox WMI.
 *
 * VBox WMI is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * VBox WMI is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with VBox WMI.  If not, see <http://www.gnu.org/licenses/>.
 */

function changePopupVisibility(elementId, isSubElement, noCloseButton)
{
    var currentElement = document.getElementById(elementId);
    var opaqueLayer = document.getElementById('opaqueLayer');
    
    if(!currentElement.style.display || currentElement.style.display == 'none')
    {
        if(!document.getElementById('popupCloseButton' + elementId) && !noCloseButton)
        {
            var closeButton = document.createElement('a');
            closeButton.setAttribute('id', 'popupCloseButton'+elementId);
            closeButton.setAttribute('class', 'popupCloseButtons');
            closeButton.setAttribute('href', 'noJavaScript.jsp');
            closeButton.setAttribute('onclick', 'return changePopupVisibility(\'' + elementId + '\', ' + isSubElement + ');');
            closeButton.innerHTML = "Close";
            currentElement.insertBefore(closeButton, currentElement.firstChild);
        }

        var parentElement = currentElement.parentNode;
        document.body.appendChild(currentElement);

        resizePopup(currentElement);

        opaqueLayer.style.display = 'block';
        parentElement.appendChild(currentElement);

        if(isSubElement)
        {
            currentElement.parentNode.appendChild(opaqueLayer.cloneNode(true));
            currentElement.style.zIndex = '9992';
        }
    }
    else
    {
        currentElement.style.display = 'none';
        if(!isSubElement)
            opaqueLayer.style.display = 'none';
        else
        {
            currentElement.parentNode.removeChild(currentElement.parentNode.lastChild);
        }
    }

    return false;
}

function saveMachineConfigurationSettings(elementId, configurationFormPrefix, isSubElement)
{
    document.getElementsByName(configurationFormPrefix + '.configure')[0].disabled = false;
    changePopupVisibility(elementId, isSubElement);

    return false;
}

function updateDiskTypeFields(parentFormId, formPrefix)
{
    var parentForm = document.getElementById(parentFormId);
    if(parentForm.elements[formPrefix + '.type'].value == '1')
    {
        parentForm.elements[formPrefix + '.size'].disabled = false;
        parentForm.elements[formPrefix + '.parentId'].disabled = true;
    }
    else if(parentForm.elements[formPrefix + '.type'].value == '2')
    {
        parentForm.elements[formPrefix + '.size'].disabled = true;
        parentForm.elements[formPrefix + '.parentId'].disabled = false;
    }
}

function updateNetworkConfigurationFields(parentFormId, formPrefix)
{
    var parentForm = document.getElementById(parentFormId);
    if(parentForm.elements[formPrefix + '.ipConfig'].value == 'dynamic')
    {
        parentForm.elements[formPrefix + '.address'].disabled = true;
        parentForm.elements[formPrefix + '.ipv4mask'].disabled = true;
        parentForm.elements[formPrefix + '.ipv6mask'].disabled = true;
    }
    else if(parentForm.elements[formPrefix + '.ipConfig'].value == 'staticV4')
    {
        parentForm.elements[formPrefix + '.address'].disabled = false;
        parentForm.elements[formPrefix + '.ipv4mask'].disabled = false;
        parentForm.elements[formPrefix + '.ipv6mask'].disabled = true;
    }
    else if(parentForm.elements[formPrefix + '.ipConfig'].value == 'staticV6')
    {
        parentForm.elements[formPrefix + '.address'].disabled = false;
        parentForm.elements[formPrefix + '.ipv4mask'].disabled = true;
        parentForm.elements[formPrefix + '.ipv6mask'].disabled = false;
    }
}

function addPortForwardingRuleForm(parentId, formPrefix)
{
    var parentElement = document.getElementById(parentId);
    var newRuleRow = document.getElementById('forwardingRuleTemplateRow').cloneNode(true);
    var numberOfNewRules = document.getElementById(formPrefix + '.numberOfNewRules');
    var currentPrefix = formPrefix + '.newRule' + numberOfNewRules.value + '.';
    
    newRuleRow.setAttribute('id', currentPrefix + 'row');
    newRuleRow.removeAttribute('class');

    var ruleElements = new Array('name', 'protocol', 'hostIP', 'hostPort', 'guestIP', 'guestPort');

    var currentChild = newRuleRow.firstChild;
    for(var i = 0; i < ruleElements.length; i++)
    {
        currentChild.firstChild.setAttribute('name', currentPrefix + ruleElements[i]);
        currentChild = currentChild.nextSibling;
    }
    var removeNewRuleLink = document.createElement('a');
    removeNewRuleLink.setAttribute('class', "actionLink");
    removeNewRuleLink.setAttribute('href', 'noJavaScript.jsp');
    removeNewRuleLink.setAttribute('onclick', 'return removeNewlyCreatedForm(\''+currentPrefix+'row\', \'' + formPrefix + '.numberOfNewRules\');');
    removeNewRuleLink.innerHTML = 'Remove';
    currentChild.appendChild(removeNewRuleLink);

    //we are not inserting the row in the table but in the tbody CHILD of the the table
    parentElement.lastChild.insertBefore(newRuleRow, parentElement.lastChild.lastChild);
    numberOfNewRules.value = parseInt(numberOfNewRules.value) + 1;

    resizePopup(parentElement);

    return false;
}

function removeNewlyCreatedForm(rowId, currentNumberElementId)
{
    var rowForRemoval = document.getElementById(rowId);
    rowForRemoval.parentNode.removeChild(rowForRemoval);

    var currentNumberElement = document.getElementById(currentNumberElementId);
    currentNumberElement.value = parseInt(currentNumberElement.value) - 1;
    
    return false;
}

function resizePopup(popupElement)
{
    popupElement.style.display = 'table';
    var elementContentWidth = popupElement.offsetWidth;
    popupElement.style.display = 'block';
    popupElement.style.width = (elementContentWidth) + 'px';
}

function changeNATConfiguration(configurationType, formPrefix, enable)
{
    var configButton = document.getElementById(formPrefix + '.button');
    var buttonOnClick = 'return changeNATConfiguration(\'' + configurationType + '\', \'' + formPrefix + '\', ' + !enable + ');';
    configButton.setAttribute('onclick', buttonOnClick);
    configButton.setAttribute('value', (enable) ? 'Cancel' : 'Modify');
    document.getElementsByName(formPrefix + '.configure')[0].disabled = !enable;

    switch(configurationType)
    {
        //main NAT configuration
        case '1':
        {
            document.getElementsByName(formPrefix + '.mtu')[0].disabled = !enable;
            document.getElementsByName(formPrefix + '.socketSend')[0].disabled = !enable;
            document.getElementsByName(formPrefix + '.socketReceive')[0].disabled = !enable;
            document.getElementsByName(formPrefix + '.initialSend')[0].disabled = !enable;
            document.getElementsByName(formPrefix + '.initialReceive')[0].disabled = !enable;
            document.getElementsByName(formPrefix + '.networkName')[0].disabled = !enable;
            document.getElementsByName(formPrefix + '.hostIp')[0].disabled = !enable;
        }break;

        //TFTP configuration
        case '2':
        {
            document.getElementsByName(formPrefix + '.prefix')[0].disabled = !enable;
            document.getElementsByName(formPrefix + '.bootFile')[0].disabled = !enable;
            document.getElementsByName(formPrefix + '.nextServer')[0].disabled = !enable;
        }break;

        //DNS configuration
        case '3':
        {
            document.getElementsByName(formPrefix + '.passHostDomain')[0].disabled = !enable;
            document.getElementsByName(formPrefix + '.dnsProxy')[0].disabled = !enable;
            document.getElementsByName(formPrefix + '.useHostResolver')[0].disabled = !enable;
        }break;

        //alias mode
        case '4':
        {
            document.getElementsByName(formPrefix)[0].disabled = !enable;
        }break;
    }

    return false;
}

function addSharedFolderForm(parentId, formPrefix)
{
    var parentElement = document.getElementById(parentId);
    var newFolderRow = document.getElementById('sharedFolderTemplateRow').cloneNode(true);
    var numberOfNewFolders = document.getElementById(formPrefix + '.newNumber');
    var currentPrefix = formPrefix + '.newFolder' + numberOfNewFolders.value + '.';

    newFolderRow.setAttribute('id', currentPrefix + 'row');
    newFolderRow.removeAttribute('class');

    var folderElements = new Array('name', 'hostPath', 'writable');

    var currentChild = newFolderRow.firstChild;
    for(var i = 0; i < folderElements.length; i++)
    {
        currentChild.firstChild.setAttribute('name', currentPrefix + folderElements[i]);
        currentChild = currentChild.nextSibling;
    }
    var removeNewFolderLink = document.createElement('a');
    removeNewFolderLink.setAttribute('class', 'actionLink');
    removeNewFolderLink.setAttribute('href', 'noJavaScript.jsp');
    removeNewFolderLink.setAttribute('onclick', 'return removeNewlyCreatedForm(\''+currentPrefix+'row\', \'' + formPrefix + '.newNumber\');');
    removeNewFolderLink.innerHTML = 'Remove';
    currentChild.appendChild(removeNewFolderLink);

    //we are not inserting the row in the table but in the tbody CHILD of the the table
    parentElement.lastChild.insertBefore(newFolderRow, parentElement.lastChild.lastChild);
    numberOfNewFolders.value = parseInt(numberOfNewFolders.value) + 1;

    resizePopup(parentElement);

    return false;
}

function addControllerForm(parentId, formPrefix)
{
    var parentElement = document.getElementById(parentId);
    var newControllerRow = document.getElementById('controllerTemplateRow').cloneNode(true);
    var numberOfNewControllers = document.getElementById(formPrefix + '.newNumber');
    var currentPrefix = formPrefix + '.newController' + numberOfNewControllers.value + '.';

    newControllerRow.setAttribute('id', currentPrefix + 'row');
    newControllerRow.removeAttribute('class');

    var controllerElements = new Array('name', 'connectionType', 'controllerType', 'hostIOCache');

    var currentChild = newControllerRow.firstChild;
    for(var i = 0; i < controllerElements.length; i++)
    {
        currentChild.firstChild.setAttribute('name', currentPrefix + controllerElements[i]);
        currentChild = currentChild.nextSibling;
    }
    
    var removeNewControllerLink = document.createElement('a');
    removeNewControllerLink.setAttribute('class', 'actionLink');
    removeNewControllerLink.setAttribute('href', 'noJavaScript.jsp');
    removeNewControllerLink.setAttribute('onclick', 'return removeNewlyCreatedForm(\''+currentPrefix+'row\', \'' + formPrefix + '.newNumber\');');
    removeNewControllerLink.innerHTML = 'Remove';
    currentChild.appendChild(removeNewControllerLink);

    //we are not inserting the row in the table but in the tbody CHILD of the the table
    parentElement.lastChild.insertBefore(newControllerRow, parentElement.lastChild.lastChild);
    numberOfNewControllers.value = parseInt(numberOfNewControllers.value) + 1;

    resizePopup(parentElement);

    return false;
}

function addAttachmentForm(parentId, formPrefix, noControllers)
{
    var parentElement = document.getElementById(parentId);
    var newAttachmentRow = document.getElementById('attachmentTemplateRow').cloneNode(true);
    var numberOfNewAttachments = document.getElementById(formPrefix + '.newNumber');
    var currentPrefix = formPrefix + '.newAttachment' + numberOfNewAttachments.value + '.';

    newAttachmentRow.setAttribute('id', currentPrefix + 'row');
    newAttachmentRow.removeAttribute('class');

    var attachmentElements = new Array('mediumId', 'controllerName', 'controllerPort', 'controllerSlot', 'deviceType');

    var currentChild = newAttachmentRow.firstChild;
    for(var i = 0; i < attachmentElements.length; i++)
    {
        currentChild.firstChild.setAttribute('name', currentPrefix + attachmentElements[i]);
        currentChild = currentChild.nextSibling;
    }

    var deviceSelection = currentChild.previousSibling.firstChild;
    deviceSelection.setAttribute('onchange', 'buildAttachmentSelectionOperations(this, \''+currentPrefix+'\');');

    var removeNewAttachmentLink = document.createElement('a');
    removeNewAttachmentLink.setAttribute('class', 'actionLink');
    removeNewAttachmentLink.setAttribute('href', 'noJavaScript.jsp');
    removeNewAttachmentLink.setAttribute('onclick',
        'return removeNewlyCreatedForm(\''+currentPrefix+'row\', \''+formPrefix+'.newNumber\');');
    removeNewAttachmentLink.innerHTML = 'Remove';
    newAttachmentRow.lastChild.appendChild(removeNewAttachmentLink);

    //we are not inserting the row in the table but in the tbody CHILD of the the table
    parentElement.lastChild.insertBefore(newAttachmentRow, parentElement.lastChild.lastChild);
    numberOfNewAttachments.value = parseInt(numberOfNewAttachments.value) + 1;

    if(!noControllers)
        buildAvailableControllersOptions(currentPrefix + 'row');

    resizePopup(parentElement);

    return false;
}

function buildAttachmentSelectionOperations(selectionElement, currentPrefix)
{
    var targetElement = selectionElement.parentNode.nextSibling;
    while(targetElement.childNodes.length >= 1)
        targetElement.removeChild(targetElement.firstChild);

    switch(selectionElement.value)
    {
        case 'HARD_DISK':
        {
            var addNewDiskLink = document.createElement('a');
            addNewDiskLink.setAttribute('class', 'actionLink');
            addNewDiskLink.setAttribute('href', 'noJavaScript.jsp');
            addNewDiskLink.setAttribute('id', currentPrefix + 'newMedium.newDiskLink');
            addNewDiskLink.setAttribute('onclick', 'return addNewDiskAttachment(\'' + currentPrefix + '\');');
            addNewDiskLink.innerHTML = 'New&nbsp;Disk';
            targetElement.appendChild(addNewDiskLink);

            targetElement.appendChild(document.createElement('br'));

            var selectDiskLink = document.createElement('a');
            selectDiskLink.setAttribute('class', 'actionLink');
            selectDiskLink.setAttribute('href', 'noJavaScript.jsp');
            selectDiskLink.setAttribute('onclick', 
                'return openResourceSelectionPopup(\'1\', \'1\', \'' + currentPrefix + 'mediumId\');');
            selectDiskLink.innerHTML = 'Select&nbsp;Disk';
            targetElement.appendChild(selectDiskLink);
        }break;

        case 'DVD':
        {
            var selectDVDLink = document.createElement('a');
            selectDVDLink.setAttribute('class', 'actionLink');
            selectDVDLink.setAttribute('href', 'noJavaScript.jsp');
            selectDVDLink.setAttribute('onclick',
                'return openResourceSelectionPopup(\'1\', \'2\', \'' + currentPrefix + 'mediumId\');');
            selectDVDLink.innerHTML = 'Select&nbsp;DVD';
            targetElement.appendChild(selectDVDLink);
        }break;

        case 'FLOPPY':
        {
            var selectFDDLink = document.createElement('a');
            selectFDDLink.setAttribute('class', 'actionLink');
            selectFDDLink.setAttribute('href', 'noJavaScript.jsp');
            selectFDDLink.setAttribute('onclick',
                'return openResourceSelectionPopup(\'1\', \'3\', \'' + currentPrefix + 'mediumId\');');
            selectFDDLink.innerHTML = 'Select&nbsp;Floppy';
            targetElement.appendChild(selectFDDLink);
        }break;
    }

    //resizes the parent popup to better fit around the changes in the content
    resizePopup(selectionElement.parentNode.parentNode.parentNode.parentNode);

    return false;
}

function buildNetworkSelectionOperations(selectionElement, currentPrefix)
{
    var targetElement = selectionElement.parentNode;
    if(targetElement.firstChild.nextSibling != null)
        targetElement.removeChild(targetElement.firstChild.nextSibling);

    switch(selectionElement.value)
    {
        case 'INTERNAL':
        {
            var selectInternalNetLink = document.createElement('a');
            selectInternalNetLink.setAttribute('class', 'actionLink');
            selectInternalNetLink.setAttribute('href', 'noJavaScript.jsp');
            selectInternalNetLink.setAttribute('onclick',
                'return openResourceSelectionPopup(\'2\', \'1\', \'' + currentPrefix + 'networkName\');');
            selectInternalNetLink.innerHTML = 'Select';
            targetElement.appendChild(selectInternalNetLink);
            document.getElementById(currentPrefix + 'networkNameInternal').disabled = false;
            document.getElementById(currentPrefix + 'networkNameExternal').disabled = true;
        }break;

        case 'BRIDGED':
        case 'HOST_ONLY':
        {
            var selectHostNetLink = document.createElement('a');
            selectHostNetLink.setAttribute('class', 'actionLink');
            selectHostNetLink.setAttribute('href', 'noJavaScript.jsp');
            selectHostNetLink.setAttribute('onclick',
                'return openResourceSelectionPopup(\'2\', \'2\', \'' + currentPrefix + 'networkName\');');
            selectHostNetLink.innerHTML = 'Select';
            targetElement.appendChild(selectHostNetLink);
            document.getElementById(currentPrefix + 'networkNameInternal').disabled = true;
            document.getElementById(currentPrefix + 'networkNameExternal').disabled = false;
        }break;

        default:
        {
            document.getElementById(currentPrefix + 'networkNameInternal').disabled = true;
            document.getElementById(currentPrefix + 'networkNameExternal').disabled = false;
        }break;
    }

    return false;
}

function openMountMediumPopup(mountFormId, controllerName, controllerPort, controllerSlot, deviceType)
{
    var mountForm = document.getElementById(mountFormId);
    mountForm.elements['controllerName'].value = controllerName;
    mountForm.elements['controllerPort'].value = controllerPort;
    mountForm.elements['controllerSlot'].value = controllerSlot;
    mountForm.elements['mediumId'].value = '';
    mountForm.elements['force'].checked = false;

    var mountMediumSelectionLink = document.getElementById('mountMediumSelectionLink');
    mountMediumSelectionLink.setAttribute('onclick', 'return openResourceSelectionPopup(\'1\', \''
                                                     + deviceType + '\', \'mediumId\');');

    changePopupVisibility(mountFormId, true);

    return false;
}

function addNewDiskAttachment(formPrefix)
{
    var currentPrefix = formPrefix + 'newMedium';

    if(!document.getElementById(currentPrefix + '.div'))
    {
        var parentElement = document.getElementById(formPrefix + 'row');
        var newDiskAttachmentElement = document.getElementById('newMediumAttachmentElement').cloneNode(true);

        newDiskAttachmentElement.setAttribute('id', currentPrefix + '.div');
        newDiskAttachmentElement.setAttribute('class', 'resourceCreationElement');

        var diskFormElements = new Array('', '.location', '.permissions', '.size', '.parentId');
        var inputChildren = newDiskAttachmentElement.getElementsByTagName('input');

        for(var i = 0; i < diskFormElements.length; i++)
            inputChildren[i].setAttribute('name', currentPrefix + diskFormElements[i]);

        var formatSelectElement = newDiskAttachmentElement.getElementsByTagName('select')[0];
        formatSelectElement.setAttribute('name', currentPrefix + '.format');

        var variantSelectElement = newDiskAttachmentElement.getElementsByTagName('select')[1];
        variantSelectElement.setAttribute('name', currentPrefix + '.variant');
        variantSelectElement.setAttribute('onchange', 'updateNewDiskFields(\'' + currentPrefix + '\');');

        var doneNewMediumLink = document.createElement('a');
        doneNewMediumLink.setAttribute('class', 'actionLink');
        doneNewMediumLink.setAttribute('href', 'noJavaScript.jsp');
        doneNewMediumLink.setAttribute('onclick', 'return changePopupVisibility(\''+currentPrefix+'.div\', true);');
        doneNewMediumLink.innerHTML = 'Done';
        newDiskAttachmentElement.appendChild(doneNewMediumLink);

        parentElement.lastChild.appendChild(newDiskAttachmentElement);
        var mediumIdInput = parentElement.firstChild.lastChild;
        mediumIdInput.disabled = true;
        mediumIdInput.value = 'n/a';

        changePopupVisibility(currentPrefix + '.div', true);
    }
    else
        changePopupVisibility(currentPrefix + '.div', true);

    document.getElementById(currentPrefix + '.newDiskLink').innerHTML = 'Modify';

    return false;
}

function buildAvailableControllersOptions(parentId)
{
    var controllerSelectElement = document.getElementById(parentId).getElementsByTagName('select')[0];
    var numberOfStorageControllers = parseInt(document.getElementsByName('modify.storage.controllers.number')[0].value);

    for(var i = 0; i < numberOfStorageControllers; i++)
    {
        var controllerName = document.getElementsByName('modify.storage.controller' + i + '.name')[0].value;
        var controllerOptionElement = document.createElement('option');
        controllerOptionElement.text = controllerName;
        controllerOptionElement.value = controllerName;
        controllerSelectElement.add(controllerOptionElement, null);
    }

    return false;
}

function setControllerPorts(selectInput)
{
    var parentRow = selectInput.parentNode.parentNode;
    var portSelection = parentRow.getElementsByTagName('select')[1];
    var slotSelection = parentRow.getElementsByTagName('select')[2];

    while(portSelection.length > 0)
        portSelection.remove(0);
    while(slotSelection.length > 0)
        slotSelection.remove(0);

    var controllerInputElements = document.getElementById('storageControllersSettingsTable').getElementsByTagName('input');

    for(var i = 0; i < controllerInputElements.length; i++)
    {
        if(controllerInputElements[i].value == selectInput.value)
        {
            var highPort = parseInt(controllerInputElements[i+1].value);
            var highSlot = parseInt(controllerInputElements[i+2].value);

            for(var ii = 0; ii < highPort; ii++)
            {
                var portOption = document.createElement('option');
                portOption.text = ii;
                portOption.value = ii;
                portSelection.add(portOption, null);
            }

            for(var iii = 0; iii < highSlot; iii++)
            {
                var slotOption = document.createElement('option');
                slotOption.text = iii;
                slotOption.value = iii;
                slotSelection.add(slotOption, null);
            }

            break;
        }
    }
}

function changeMachineCreationElementState(elementId, configurationStateInput)
{
    if(configurationStateInput.checked)
    {
        var modificationLink = document.createElement('a');
        modificationLink.setAttribute('class', 'actionLink');
        modificationLink.setAttribute('id', 'modificationLink.' + elementId);
        modificationLink.setAttribute('href', 'noJavaScript.jsp');
        modificationLink.setAttribute('onclick', 'return changePopupVisibility(\'' + elementId + '\');');
        modificationLink.innerHTML = 'Modify';
        configurationStateInput.parentNode.nextSibling.appendChild(modificationLink);

        changePopupVisibility(elementId);
    }
    else
        configurationStateInput.parentNode.nextSibling.removeChild(document.getElementById('modificationLink.' + elementId));
}

function addNetworkAdapterForm(parentId)
{
    var numberOfNetworkAdapters = document.getElementsByName('create.machine.networks.numberOfEnabledAdapters')[0];

    if(parseInt(numberOfNetworkAdapters.value) <= 7)
    {
        var parentElement = document.getElementById(parentId);
        var newAdapterTable = document.getElementById('networkAdapterTemplate').cloneNode(true);
        var currentFormPrefix = 'create.machine.adapter' + numberOfNetworkAdapters.value;
        newAdapterTable.setAttribute('id', currentFormPrefix);
        newAdapterTable.setAttribute('class', 'resourceCreationElement');

        var inputElements = newAdapterTable.getElementsByTagName('input');
        var inputElementsNames = new Array('.enabled', '.adapterState', '.MAC', '.networkName', '.networkName', '.lineSpeed', '.cable');
        for(var i = 0; i < inputElements.length; i++)
            inputElements[i].setAttribute('name', currentFormPrefix + inputElementsNames[i]);

        inputElements[3].setAttribute('id', currentFormPrefix + '.networkNameExternal');
        inputElements[4].setAttribute('id', currentFormPrefix + '.networkNameInternal');

        var selectElements = newAdapterTable.getElementsByTagName('select');
        var selectElementsNames = new Array('.adapterType', '.attachmentType');
        for(var ii = 0; ii < selectElements.length; ii++)
            selectElements[ii].setAttribute('name', currentFormPrefix + selectElementsNames[ii]);

        selectElements[1].setAttribute('onchange', 'buildNetworkSelectionOperations(this, \'' + currentFormPrefix + '.\');');

        var doneLink = document.createElement('a');
        doneLink.setAttribute('class', 'actionLink');
        doneLink.setAttribute('href', 'noJavaScript.jsp');
        doneLink.setAttribute('onclick', 'return changePopupVisibility(\'' + currentFormPrefix + '\', true);');
        doneLink.innerHTML = 'Done';
        //table________.tbody____.tr_______.td________.
        newAdapterTable.lastChild.lastChild.firstChild.appendChild(doneLink);


        var newAdapterRow = document.createElement('tr');
        newAdapterRow.setAttribute('id', 'newAdapterRow' + numberOfNetworkAdapters.value);
        var newAdapterCell = document.createElement('td');
        newAdapterCell.innerHTML = 'Adapter&nbsp;#' + numberOfNetworkAdapters.value;
        newAdapterRow.appendChild(newAdapterCell);

        var openAdapterLink = document.createElement('a');
        openAdapterLink.setAttribute('class', 'actionLink');
        openAdapterLink.setAttribute('href', 'noJavaScript.jsp');
        openAdapterLink.setAttribute('onclick', 'return changePopupVisibility(\'' + currentFormPrefix + '\', true);');
        openAdapterLink.innerHTML = 'View';
        newAdapterCell = document.createElement('td');
        newAdapterCell.appendChild(openAdapterLink);
        newAdapterRow.appendChild(newAdapterCell);

        newAdapterCell = document.createElement('td');
        newAdapterCell.appendChild(newAdapterTable);
        newAdapterRow.appendChild(newAdapterCell);

        parentElement.insertBefore(newAdapterRow, document.getElementById('networkAdaptersAdditionLinkRow').parentNode);
        numberOfNetworkAdapters.value = parseInt(numberOfNetworkAdapters.value) + 1;

        resizePopup(parentElement);
    }

    return false;
}

function updateNewDiskFields(formPrefix)
{
    var variantField = document.getElementsByName(formPrefix + '.variant')[0];
    var sizeField = document.getElementsByName(formPrefix + '.size')[0];
    var parentIdField = document.getElementsByName(formPrefix + '.parentId')[0];

    if(variantField.value == 'DIFF')
    {
        sizeField.disabled = true;
        parentIdField.disabled = false;
    }
    else
    {
        sizeField.disabled = false;
        parentIdField.disabled = true;
    }
}

function openResourceSelectionPopup(resourceType, resourceSubtype, targetFieldName)
{
    var resourcePage = null;
    var pageTitle = null;
    switch(parseInt(resourceType))
    {
        case 1:
        {
            resourcePage = 'media.jsp?type=' + resourceSubtype;
            pageTitle = 'Medium Selection';
        }break;

        case 2:
        {
            resourcePage = 'networks.jsp?type=' + resourceSubtype;
            pageTitle = 'Network Selection';
        }break;

        case 3:
        {
            resourcePage = 'machines.jsp';
            pageTitle = 'Machine Selection';
        }break;
    }

    window.open(resourcePage + '&targetFieldName=' + targetFieldName,
                pageTitle,
                'height=550,width=750,toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes');

    return false;
}

function makeResourceSelection(targetFieldName, resourceId)
{
    var targetField = opener.document.getElementsByName(targetFieldName)[0];
    targetField.value = resourceId;
    targetField.disabled = false;

    self.close();
}

function makeNetworkResourceSelection(targetFieldName, networkId, networkName)
{
    var targetFieldExternal = opener.document.getElementsByName(targetFieldName)[0];
    var targetFieldInternal = opener.document.getElementsByName(targetFieldName)[1];
    targetFieldExternal.value = networkName;
    targetFieldInternal.value = networkId;

    self.close();
}

function resourceRemovalVerification(resourceName, callerObject)
{
    var confirmationPopup = document.createElement('div');
    confirmationPopup.setAttribute('id', 'confirmationPopup');
    var popupText = document.createElement('p');
    popupText.innerHTML = 'Are you sure you want to remove ' + resourceName + '?';
    confirmationPopup.appendChild(popupText);

    var positiveAnswerLink = document.createElement('a');
    positiveAnswerLink.setAttribute('class', 'actionLink');
    positiveAnswerLink.setAttribute('href', callerObject.getAttribute('href'));
    positiveAnswerLink.innerHTML = 'Yes';
    confirmationPopup.appendChild(positiveAnswerLink);

    var negativeAnswerLink = document.createElement('a');
    negativeAnswerLink.setAttribute('class', 'actionLink');
    negativeAnswerLink.setAttribute('href', '#');
    negativeAnswerLink.setAttribute('onclick', 'return removeVerificationPopup(\'confirmationPopup\');');
    negativeAnswerLink.innerHTML = 'Cancel';
    confirmationPopup.appendChild(negativeAnswerLink);

    document.body.appendChild(confirmationPopup);
    changePopupVisibility('confirmationPopup', false, true);

    return false;
}

function removeVerificationPopup(popupId)
{
    changePopupVisibility(popupId);
    var confirmationPopup = document.getElementById(popupId);
    confirmationPopup.parentNode.removeChild(confirmationPopup);

    return false;
}

function selectionWindowModification(resourcesElementId)
{
    var resourcesElement = document.getElementById(resourcesElementId);
    resourcesElement.style.position = 'absolute';
    resourcesElement.style.top = '0px';
    resourcesElement.style.left = '0px';
    resourcesElement.style.zIndex = '9999';
    
    var opaqueLayer = document.getElementById('opaqueLayer');
    opaqueLayer.style.opacity = '1';
    opaqueLayer.style.display = 'block';
    opaqueLayer.style.backgroundColor = '#cccccc';

    //window.resizeTo(document.width + 50, document.height + 50);//doesnt work in firefox
}

function ElementsTablePagination(tableId, objectVariableName)
{
    var DEFAULT_MAX_ITEMS_PER_PAGE = 20;
    var MAX_PAGE_LINKS_AWAY_FROM_CURRENT = 5;

    var paginatedTable = document.getElementById(tableId);
    var tableRows = paginatedTable.getElementsByTagName('tr');
    var itemsPerPage = DEFAULT_MAX_ITEMS_PER_PAGE;
    var currentPage = 0;
    var numberOfPages = 0;
    var navigationElement = document.createElement('div');

    calculatePagesNumber();
    disableAllElements();
    enableCurrentPageElements();
    paginatedTable.parentNode.insertBefore(navigationElement, paginatedTable.nextSibling);
    rebuildNavigationElement();

    function calculatePagesNumber()
    {
        if((tableRows.length - 1) % itemsPerPage > 0)
            numberOfPages = parseInt((tableRows.length - 1) / itemsPerPage) + 1;
        else
            numberOfPages = (tableRows.length - 1) / itemsPerPage;
    }
    
    function disableAllElements()
    {
        //skipping the header row
        for(var i = 1; i < tableRows.length; i++)
            tableRows[i].style.display = 'none';
    }

    function enableAllElements()
    {
        //skipping the header row
        for(var i = 1; i < tableRows.length; i++)
            tableRows[i].style.display = 'table-row';
    }

    function disableCurrentPageElements()
    {
        var currentPageStartElement = (currentPage * itemsPerPage) + 1;
        var currentPageEndElement = currentPageStartElement + itemsPerPage;

        for(var i = currentPageStartElement; i < currentPageEndElement; i++)
        {
            if(tableRows[i] != null)
                tableRows[i].style.display = 'none';
            else
                return;
        }
    }

    function enableCurrentPageElements()
    {
        var currentPageStartElement = (currentPage * itemsPerPage) + 1;
        var currentPageEndElement = currentPageStartElement + itemsPerPage;

        for(var i = currentPageStartElement; i < currentPageEndElement; i++)
        {
            if(tableRows[i] != null)
                tableRows[i].style.display = 'table-row';
            else
                return;
        }
    }

    function rebuildNavigationElement()
    {
        while(navigationElement.childNodes.length > 0)
            navigationElement.removeChild(navigationElement.childNodes[0]);

        //previous page link
        if(currentPage != 0)
        {
            var firstPageLink = document.createElement('a');
            firstPageLink.setAttribute('class', 'actionLink');
            firstPageLink.setAttribute('href', 'noJavaScript.jsp');
            firstPageLink.setAttribute('onclick', 'return ' + objectVariableName + '.getPage(\'0\');');
            firstPageLink.innerHTML = 'First';
            navigationElement.appendChild(firstPageLink);

            var previousPageLink = document.createElement('a');
            previousPageLink.setAttribute('class', 'actionLink');
            previousPageLink.setAttribute('href', 'noJavaScript.jsp');
            previousPageLink.setAttribute('onclick', 'return ' + objectVariableName + '.previousPage();');
            previousPageLink.innerHTML = 'Previous';
            navigationElement.appendChild(previousPageLink);
        }

        for(var i = parseInt(currentPage) - MAX_PAGE_LINKS_AWAY_FROM_CURRENT;
            i < parseInt(currentPage); i++)
        {
            if(i >= 0)
            {
                var leftPageLink = document.createElement('a');
                leftPageLink.setAttribute('class', 'actionLink');
                leftPageLink.setAttribute('href', 'noJavaScript.jsp');
                leftPageLink.setAttribute('onclick', 'return ' + objectVariableName + '.getPage(\'' + i + '\');');

                leftPageLink.innerHTML = i + 1;
                navigationElement.appendChild(leftPageLink);
            }
        }

        var currentPageLink = document.createElement('a');
        currentPageLink.setAttribute('class', 'actionLink');
        currentPageLink.setAttribute('href', 'noJavaScript.jsp');
        currentPageLink.setAttribute('onclick', 'return ' + objectVariableName + '.getPage(\'' + currentPage + '\');');
        currentPageLink.innerHTML = '(' + (parseInt(currentPage) + 1) + ')';
        navigationElement.appendChild(currentPageLink);

        for(var ii = (parseInt(currentPage) + 1); 
            ii < parseInt(currentPage) + MAX_PAGE_LINKS_AWAY_FROM_CURRENT && ii < numberOfPages;
            ii++)
        {
            var rightPageLink = document.createElement('a');
            rightPageLink.setAttribute('class', 'actionLink');
            rightPageLink.setAttribute('href', 'noJavaScript.jsp');
            rightPageLink.setAttribute('onclick', 'return ' + objectVariableName + '.getPage(\'' + ii + '\');');

            rightPageLink.innerHTML = ii + 1;
            navigationElement.appendChild(rightPageLink);
        }


        //next page link
        if(currentPage < numberOfPages - 1)
        {
            var nextPageLink = document.createElement('a');
            nextPageLink.setAttribute('class', 'actionLink');
            nextPageLink.setAttribute('href', 'noJavaScript.jsp');
            nextPageLink.setAttribute('onclick', 'return ' + objectVariableName + '.nextPage();');
            nextPageLink.innerHTML = 'Next';
            navigationElement.appendChild(nextPageLink);

            var lastPageLink = document.createElement('a');
            lastPageLink.setAttribute('class', 'actionLink');
            lastPageLink.setAttribute('href', 'noJavaScript.jsp');
            lastPageLink.setAttribute('onclick', 'return ' + objectVariableName + '.getPage(\'' + (numberOfPages - 1) + '\');');
            lastPageLink.innerHTML = 'Last';
            navigationElement.appendChild(lastPageLink);
        }
    }

    this.nextPage = function()
    {
        if(currentPage < numberOfPages - 1)
        {
            disableCurrentPageElements();
            currentPage++;
            enableCurrentPageElements();
            rebuildNavigationElement();
        }

        return false;
    }

    this.previousPage = function()
    {
        if(currentPage > 0)
        {
            disableCurrentPageElements();
            currentPage--;
            enableCurrentPageElements();
            rebuildNavigationElement();
        }

        return false;
    }

    this.getPage = function(pageNumber)
    {
        if(pageNumber >= 0 && pageNumber < numberOfPages)
        {
            disableCurrentPageElements();
            currentPage = pageNumber;
            enableCurrentPageElements();
            rebuildNavigationElement();
        }

        return false;
    }

    this.setMaxNumberOfItemsPerPage = function(maxItems)
    {
        maxItems = parseInt(maxItems);
        if(maxItems > 0)
        {
            disableAllElements();
            itemsPerPage = maxItems;
            calculatePagesNumber();
            this.getPage(0);
            rebuildNavigationElement();
        }
        else
            this.setMaxNumberOfItemsPerPage(tableRows.length - 1);

        return false;
    }
}
